<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }
    canvas {
      display: block;
    }
  
  </style>
</head>
<body>
  <canvas></canvas>

  <script>
    var canvas = document.querySelector('canvas')
    var 
      width = window.innerWidth, 
      height = window.innerHeight

    canvas.width = width
    canvas.height = height 
    var ctx = canvas.getContext('2d')

    var
      num = 200
      
    function random (x, y) {
      return Math.floor(Math.random() * (y - x)) + x
    }

    function Ball () {
      var r = random(8, 13)
      this.x = random(r, width - r)
      this.y = random(r, height - r)
      this.r = r
      this.sx = Math.random() > 0.5 ? -random(2, 4) : random(2, 4)
      this.sy = Math.random() > 0.5 ? -random(2, 4) : random(2, 4)
      this.color = 'rgba(' + random(0, 255) + ', ' + random(0, 255) + ', ' + random(0, 255) + ', 1)'
    }


    function craeteBalls (num) {
      var balls = []
      for (var i = 0;i < num; i++) {
        balls.push(new Ball())
      }
      return balls
    }


    function draw (balls) {
      for (var i = 0; i < balls.length; i++) {
        var ball = balls[i]
        ctx.beginPath()
        ctx.fillStyle = ball.color
        ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI)
        ctx.fill()
        ctx.closePath()
      }
    }

    function move (balls) {
      for (var i = 0; i < balls.length; i++) {
        var ball = balls[i]
        if (ball.x >= width - ball.r || ball.x <= ball.r) {
          ball.sx = -ball.sx
        }

        if (ball.y >= height - ball.r || ball.y <= ball.r) {
          ball.sy = -ball.sy
        }

        ball.x += ball.sx
        ball.y += ball.sy
      }
    }

    function clear () {
      ctx.clearRect(0, 0, width, height)
    }

    function init() {
      // 生成是个球数组
      var balls = craeteBalls(num)
      draw(balls)
      setInterval(function () {
        clear()
        move(balls)
        draw(balls)
      }, 1000 / 60)
    }
    
    init()
  </script>
</body>
</html>